import { isDev } from "../../config";
import { prepayJsapi, reSign } from "../../utils/pay/wxpay-partner";
import { api } from "./api";

export async function onOrderHook(body) {
  try {
    const { name, row, prev } = body;
    if (!row) return;
    const data = {};
    for (const key in prev) {
      if (key in row) data[key] = row[key];
    }
    let oid = row.id;
    const isLogNew =
      name == "order-log-update" && (data.paid || data.fee || data.status);
    if (isLogNew) {
      oid = row.oid;
    }
    if (data.used_times > 0 || isLogNew) {
      global.sendRoomMsg("order-" + oid, "info", {
        // order: data,
        refresh: 1,
      });
    }
  } catch (error) {
    console.log("order-hook", error.message);
  }
}

export async function getFeePrepay(body, ip, notify_url) {
  if (!body.id) {
    throw "缺少参数";
  }
  const row = await api.getOrderLog({
    id: body.id,
  });
  if (!row) {
    throw "核销记录不存在";
  }
  if (row.fee != body.fee) {
    throw "超时费用已变动，请重新进入";
  }
  const reusePay = Date.now() - row.updatedAt < 3600e3;
  if (!row.paid && row.pay_info && reusePay) {
    const payment = row.pay_info;
    reSign(payment);
    return {
      payment,
    };
  }
  const shop = await api.getShopRow(row.sid);
  const user = await api.getUserInfo(row.userId);
  if (!shop || !user) {
    throw "数据出错";
  }
  let ord_no = row.ord_no;
  const mat = /^(\d+_\d+)/.exec(ord_no);
  if (mat) {
    ord_no = mat[1] + "_" + (row.fee + "").replace(".", "");
  }
  const params = {
    description: "真冰乐园-超时费用",
    out_trade_no: ord_no,
    amount: {
      total: row.fee * 100,
    },
    settle_info: {
      profit_sharing: true,
    },
    payer: {
      sp_openid: user.openid,
    },
    notify_url,
    scene_info: {
      payer_client_ip: ip,
      device_id: user.id + "",
    },
    sub_mchid: shop.mch_id,
  };
  const payment = await prepayJsapi(params);
  await api.postOrderLog({
    id: row.id,
    ord_no,
    pay_info: {
      ...payment,
      paySign: null,
    },
  });
  return {
    payment,
  };
}

export async function onOrderUse(body, user) {
  const { oid, utimes = 1, hand_no, face_img } = body;
  if (!oid) {
    throw "缺少参数";
  }
  const ordRow = await api.getOrder(oid);
  if (!ordRow) {
    throw "订单不存在";
  }
  if (ordRow.sid != user.sid && !isDev) {
    throw "无权限";
  }
  if (!ordRow.paid && !ordRow.mobile) {
    throw "订单未支付或已退款";
  }
  let rest = 2;
  if (ordRow.endAt) {
    if (Date.now() > ordRow.endAt) {
      throw "已过有效期";
    }
  } else {
    rest = ordRow.total_times - ordRow.used_times;
    if (!(rest > 0)) {
      throw "次数已用完";
    }
  }
  if (ordRow.used_times + 1 != utimes) {
    throw "次数校验出错，请让用户退出重进";
  }
  if (hand_no) {
    const nfc = await api.getNfcRow({
      sid: ordRow.sid,
      seq: hand_no,
    });
    if (!nfc) {
      throw "手环未录入";
    } else {
      if (nfc.oid) {
        throw `手环${hand_no}已被使用`;
      }
      await api.postNfc({
        id: nfc.id,
        oid,
      });
    }
  }
  rest--;
  await api.postOrderLog({
    ...body,
    ord_no: ordRow.order_no + "_" + utimes,
    sid: ordRow.sid,
    userId: ordRow.userId,
  });
  await api.postOrder({
    id: oid,
    used_times: ordRow.used_times + 1,
    status: rest > 0 ? 2 : 3,
  });
  if (face_img) {
    await api.postUserInfo({
      id: ordRow.userId,
      faceImg: face_img,
    });
  }

  return {
    oid,
    rest,
  };
}

export async function onOrderLogDone(body, pay_info) {
  if (!body.id && !body.ord_no) {
    throw "缺少参数";
  }
  const row = await api.getOrderLog(body);
  if (!row) {
    throw "核销记录不存在";
  }
  const nfc = await api.getNfcRow({
    sid: row.sid,
    seq: row.hand_no,
  });
  if (nfc) {
    await api.postNfc({
      id: nfc.id,
      oid: null,
    });
  }
  delete body.ord_no;
  const logBody = {
    id: row.id,
    status: 2,
  };
  if (pay_info) {
    logBody.pay_info = pay_info;
    logBody.paid = true;
  }
  const data = await api.postOrderLog(logBody);
  return data;
}
